package com.fhzn.auth.tools;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author fhzn
 */
public class Md5HashUtil {

    /**
     * MD5 加密算法
     */
    public static String toMd5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buf;
            buf = md.digest(str.getBytes(StandardCharsets.UTF_8));
            return toHexString(buf);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static final char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static String toHexString(byte[] bytes) {
        int length = bytes.length;
        StringBuilder sb = new StringBuilder(length * 2);
        int x;
        int n1, n2;
        for (byte aByte : bytes) {
            if (aByte >= 0) {
                x = aByte;
            } else {
                x = 256 + aByte;
            }
            n1 = x >> 4;
            n2 = x & 0x0f;
            sb.append(HEX[n1]);
            sb.append(HEX[n2]);
        }
        return sb.toString();
    }
}
